/**  
 * All rights Reserved, Designed By <a href="www.itttq.com" target="_blank">www.itttq.com</a>
 * @date:   2017-07-21 11:42:21
 * @Copyright: 2017 <a href="www.itttq.com" target="_blank">www.itttq.com</a> Inc. All rights reserved. 
 */
package com.itttq.gshop.pc.controller.user;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.itttq.gshop.domain.po.UserAddressPo;
import com.itttq.gshop.domain.po.UserInfoPo;
import com.itttq.gshop.domain.to.ResultDataTo;
import com.itttq.gshop.domain.to.ResultTo;
import com.itttq.gshop.generic.cmpt.annotation.Auth;
import com.itttq.gshop.generic.connector.IUserAddressConnector;
import com.itttq.gshop.pc.controller.GenericPcController;
@Auth
@RestController
@RequestMapping("address")
public class AddressController extends GenericPcController {
	private static final long serialVersionUID = -6485775841311449L;
	public static final String cacheKey = "userAddress";
	@Autowired
	private IUserAddressConnector userAddressConnector;
	/**
	 * 获取当前登录用户的所有收货地址
	 * 
	 * @param request
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("list.html")
    public ModelAndView getAddresses(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/mine/address");
		UserAddressPo userAddress = new UserAddressPo();
		userAddress.setUserId(this.getUserIdFromSession(request));
		mv.addObject("addrs", userAddressConnector.getUserAddresss(userAddress).getData());
		getCommon(request, mv);
        return mv;
    }
	/**
	 * 根据ID获取地址
	 * 
	 * @param id
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("{id}.html")
	public ResultDataTo<UserAddressPo> getUserAddressById(@PathVariable("id") int id) {
		ResultDataTo<UserAddressPo> rt = new ResultDataTo<UserAddressPo>();
		try {
			rt.setData(userAddressConnector.getUserAddress(id));
		} catch (Exception e) {
			rt.setCode(ResultTo.FAIL);
		}
		return rt;
	}
	
	/**
	 * 保存收货地址，有ID则更新数据，没有则新建数据
	 * 
	 * @param addr
	 * @Author 迷蝶
	 * @return ResultTo 如果成功，则msg放新ID
	 */
	@RequestMapping("save.html")
	public ResultTo saveUserAddress(UserAddressPo addr, HttpServletRequest request) {
		ResultTo rt = new ResultTo();
		UserInfoPo user = this.getUserFromSession(request);
		addr.setUserId(user.getId());
		addr.setUserName(user.getUsername());
		if(userAddressConnector.saveUserAddress(addr) < 1) {
			rt.setCode(ResultTo.FAIL);
		} else {
			rt.setMsg(String.valueOf(addr.getId()));
		}
		return rt;
	}

	@RequestMapping("del/{id}.html")
	public Integer delUserAddress(@PathVariable("id") int id) {
		return userAddressConnector.delUserAddress(id);
	}
}